<template>
  <!--
    基本表单验证
     表单元素值双向绑定
      el-form
          model:整个表单元素值的对象
          rules:规则
             rules:{
                prop的值
                username:[
                  {required:true,message:'错误信息',trigger:'blur/change'},
                  {min:最小长度,max:最大长度,message:'错误信息',trigger:'blur/change'},
                  {
                    pattern:正则表达式,message:'错误信息',trigger:'blur/change'
                  }
                ],
                password:[
                 {required:true,message:'错误信息',trigger:'blur/change'}
                ]
             }
      el-form-item
          prop:需要验证项的值的字段名
   -->
  <!-- 全局表单验证
             点击按钮触发所有表单项的验证
             ref:
                1:获取原生标签的dom
                2:获取组件的this
              xxx.vue   methods:{test(){}}
              <xxx ref='xxx' />  this.$refs.xxx.test()
            1:el-form  ref="form"
            2:this.$refs.form.validate((result)=>{
              result:true:验证通过  false:验证失败
            })   -->

  <div>
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item>
        <el-button @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '必填', trigger: 'change' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请正确输入手机号',
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 6, max: 12, message: '请输入6-12位密码', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    async submit() {
      this.$refs.form.validate((result) => {
        // result:验证结果 true:成功  false:失败
        console.log(result)
      })
      // try {
      // const res = await this.$refs.form.validate()
      // console.log('成功', res)
      // } catch (err) {
      //   console.log('失败', err)
      // }
    }
  }
}
</script>
<style></style>
